package com.example.demo.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpStatus;
import com.example.demo.util.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

@Slf4j
@RestController
public class PhoneNumberController {

   @Value("${config.thread-core}")
   private String threadCore;

    @GetMapping("/queryBelong")
    public Object queryBelong(String phoneNumber) throws ExecutionException, InterruptedException {
        Map data = new HashMap();
        List<String> strings = Arrays.asList(phoneNumber.replaceAll(" ", ",").split(","));
        List<String> urls = new ArrayList<>();
        for (String s : strings) {
            urls.add("http://weixin.170cz.cn/weixin/qm/numbercheck?state=A3540588/l6x9&phone=" + s + "-" + "http://weixin.170cz.cn/weixin/query/balance?state=A3540588/l6x9&phone=" + s);
        }
        ExecutorService executor = Executors.newFixedThreadPool(Integer.valueOf(threadCore));
        List list = new ArrayList();
        Future<List> submit = null;
        log.info("线程开始执行--------------");
        for (String url : urls) {
            Map map = new HashMap();
            submit = executor.submit(() -> {
                // 开始调用具体业务代码
                String[] split = url.split("-");
                Map numbercheck = JSONUtil.readValue(HttpRequest.post(split[0]).execute().body(), Map.class);
                Map balance = JSONUtil.readValue(HttpRequest.post(split[1]).execute().body(), Map.class);
                map.put("phoneNumber", split[0].split("&phone=")[1]);
                map.put("province", numbercheck.get("province"));
                map.put("city", numbercheck.get("city"));
                map.put("operator", numbercheck.get("operator"));
                if (balance.get("return").equals("success")) {
                    map.put("balance", balance.get("balance"));
                    map.put("name", balance.get("name"));
                }
                list.add(map);
            }, list);
        }
        log.info("当前线程数据{}", submit.get());
        log.info("线程结束执行--------------");
        executor.shutdown();
        data.put("data", list);
        data.put("code", HttpStatus.HTTP_OK);
        return data;
    }

}
